package com.itheima.stargraph.interception;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpStatus;
import com.itheima.stargraph.pojo.User;
import com.itheima.stargraph.utils.JWTUtils;
import com.itheima.stargraph.utils.UserThreadlocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * TODO
 *
 * @Author mr.wu
 * @Data #{DATE} #{TIME}
 */
@Component
public class UserInterception implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        String token = request.getHeader(HttpHeaders.AUTHORIZATION);
        if(StrUtil.isBlank(token)){
            response.setStatus(HttpStatus.HTTP_UNAUTHORIZED);
            throw new RuntimeException("请先登录");
        }
        boolean result = JWTUtils.verify(token);
        if(!result){
            response.setStatus(HttpStatus.HTTP_UNAUTHORIZED);
            throw new RuntimeException("请先登录");
        }
        User user = JWTUtils.getUser(token);
        UserThreadlocalUtil.setUser(user);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadlocalUtil.remove();
    }
}
